# -*- coding: utf-8 -*-
# https://blog.csdn.net/weixin_52040868
# 公众号：测个der
# 微信：qing_an_an

import threading
import queue
import time
import serial
import msvcrt


class SerialTerminal(object):
    total_length = 0

    def __init__(self, COM, PORT):
        self.COM = COM
        self.PORT = PORT
        self.recv_queue = queue.Queue()
        self.write_queue = queue.Queue()


    def Getch(self):
        """Get Keyboard Byte"""
        return msvcrt.getch().decode()


    def Start(self):
        """RUN"""
        self.ser = serial.Serial(self.COM, self.PORT)  # 不使用数据终端准备  # 设置串口名称和波特率
        self.ser.write(f"\n".encode())

        self.Read_thread = threading.Thread(target=self.Read_serial)
        self.Read_thread.daemon = True
        self.Read_thread.start()

        self.Write_thread = threading.Thread(target=self.Write_serial)
        self.Write_thread.daemon = True
        self.Write_thread.start()

        # 主线程等待键盘输入
        while True:
            ch = self.Getch()
            # if ch == b'q':
            if ord(ch) == 3:  # 按下Ctrl+C键的ASCII码为3
                # ESC退出循环
                break
            self.ser.write(ch.encode())

    def Read_serial(self):

        while True:
            try:
                count = self.ser.inWaiting()
                if count != 0:
                    # 读取内容并放入队列
                    recv = self.ser.readline()
                    # recv = self.ser.read_all()
                    recv_str = recv.decode()
                    print(recv_str, end="", flush=True)
                    self.write_queue.put(recv_str)
            except UnicodeDecodeError as e:
                pass

    def Write_serial(self):
        write_count = 0  # 初始化写入计数器
        while True:
            # time_ = time.strftime('%H:%M:%S')
            try:
                # 从写入队列中取出数据并写入文件
                recv = self.write_queue.get()
                # with open("ddd.txt", 'a', encoding='utf-8') as w:
                #     w.write(f'[{time_}]' + recv)
                with open("ddd.txt", 'a', encoding='utf-8') as w:
                    w.write(recv.strip('\n'))
                    write_count += len(recv)  # 累加写入的字符串长度
                    # if write_count > 0:
                    if '3v3en' in recv:     # 输出统计字节
                        print(f"Total number of times this time: {write_count}")
                    if '3v3en' in recv:
                        write_count = 0  # 重置总写入计数器
            except queue.Empty:
                pass



if __name__ == '__main__':
    ter = SerialTerminal('COM3', 115200)
    ter.Start()